package com.itheima.advice;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.HolderThread;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
public class RecordLogAdvice {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(log)")
    public Object recordLog(ProceedingJoinPoint pjp, LogOperation log) throws Throwable{
        Long begin = System.currentTimeMillis();
        Object returnValue = pjp.proceed();
        Long end = System.currentTimeMillis();
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        OperateLog operateLog = new OperateLog();
        operateLog.setOperateEmpId(getCurrentUserId());//当前登录人先写死1
        operateLog.setOperateTime(LocalDateTime.now());//操作时间
        operateLog.setClassName(pjp.getTarget().getClass().getName());//类名
        operateLog.setMethodName(signature.getMethod().getName());//方法名
        operateLog.setMethodParams(pjp.getArgs()==null?"":pjp.getArgs().toString());//方法参数
        operateLog.setReturnValue(returnValue==null?"":returnValue.toString());//方法返回值
        operateLog.setCostTime(end-begin);
        operateLogMapper.insert(operateLog);
        return returnValue;
    }

    private Integer getCurrentUserId() {
        return HolderThread.getId();
    }

}
